import React, { Component } from 'react';
import logo from './logo.svg';
import Button from '@material-ui/core/Button';
import $ from 'jquery';

import './App.css';

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      uploadName: null,
      processedName: null
    }
    this.prefix = 'http://localhost:4567/fuck/'
  }

  upload_img = () => {
    console.log('Click me')
    const input_img = document.getElementById('img_to_upload').files[0]
    const fd = new FormData()
    const me = this
    fd.append('img', input_img)
    $.ajax({
      url: '/upload',
      data: fd,
      type: 'POST',
      contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
      processData: false, // NEEDED, DON'T OMIT THIS
      dataType: 'json'
    }).then(res => {
      const url = res.url
      // $('#show').html('<img src="http://localhost:4567/fuck/'+url+'"></img>')
      me.setState({ uploadName: url })
    })
  }

  salt = () => {
    console.log("TODO: complete salt function")
    const me = this
    $.ajax({
      url: '/process',
      data: { name: this.state.uploadName },
      type: 'POST',
      dataType: 'json'
    }).then(res => {
      if (res.ok) {
        const url = res.url
        // $('#show').html('<img src="http://localhost:4567/fuck/'+url+'"></img>')
        me.setState({ processedName: url })
      }
    })
  }


  render() {
    const show = this.state.uploadName == null ? (<div>No input</div>) : (<img src={this.prefix + this.state.uploadName}></img>)
    const output = this.state.processedName == null ? (<div>No output</div>) : (<img src={this.prefix + this.state.processedName}></img>)
    return (
      <div className="main">
        <div>
          <div>Input img</div>
          <div><input id="img_to_upload" name="myFile" type="file" accept=".jpg, .jpeg, .png" /></div>
          <div><button onClick={this.upload_img}>Upload</button></div>
          <div id="show">
            {show}
          </div>
        </div>
        <div>
          <button onClick={this.salt}>Salt</button>
        </div>
        <div>
          {output}
        </div>
      </div>
    );
  }
}

export default App;
